package com.sunsy.authserver.interceptor;

import com.alibaba.fastjson.JSON;
import com.sunsy.authserver.beans.po.UniformUser;
import com.sunsy.authserver.constants.UserContextHolder;
import com.sunsy.authserver.dao.UserTokenDao;
import com.sunsy.authserver.enums.ErrorCode;
import com.sunsy.authserver.util.JwtUtil;
import com.sunsy.authserver.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sunsy.authserver.constants.ApiConstants.User.USER_ID;
import static com.sunsy.authserver.constants.ApiConstants.User.USER_NAME;

/**
 * 登录拦截器，设置上下文信息
 *
 * @author 孙思远
 * @date 2021/7/19
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserTokenDao userTokenDao;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 不过滤的资源
     */
    @Value("${zuul.white_url}")
    private ArrayList nofilter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        boolean flag = Tools.isNofilter(request,nofilter);
        if (flag){
            return true;
        }
        String userToken = request.getHeader("user_token");
        String url = request.getRequestURI();
        if (StringUtils.isNotBlank(userToken)) {
            if (!jwtUtil.verify(userToken)){
                ErrorCode.USER_TOKEN_DENIED.apiExc();
            }
            Map<String, Object> user = userTokenDao.getUserByUserToken(userToken);
            UserContextHolder.getInstance().setContext(user);
            if (url.contains("admin")) {//如果是管理员接口，判断一下当前登陆人的
                if (!"ADMIN".equals(String.valueOf(user.get("type")))) {
                    ErrorCode.PERMISSION_DENIED.apiExc();
                    return false;
                }
            }
        } else if (url.contains("admin")) {
            ErrorCode.PERMISSION_DENIED.apiExc();
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        UserContextHolder.getInstance().clear();
    }
}
